﻿using System;
using System.Web;
using NHibernate;
using NHibernate.Context;
using JSC.Data.NHibernate;

namespace JSC.Portal.Web.HttpModules
{
	public class NHibernateSessionModule : IHttpModule
	{
		public void Init(HttpApplication context)
		{
			context.BeginRequest += new EventHandler(Application_BeginRequest);
			context.EndRequest += new EventHandler(Application_EndRequest);
		}

		public void Dispose()
		{
		}

		private void Application_BeginRequest(object sender, EventArgs e)
		{
			ManagedWebSessionContext.Bind(HttpContext.Current, NHibernateSession.SessionFactory.OpenSession());
		}

		private void Application_EndRequest(object sender, EventArgs e)
		{
			ISession session = ManagedWebSessionContext.Unbind(HttpContext.Current, NHibernateSession.SessionFactory);
			if (session == null)
				return;
			if (session.Transaction.IsActive)
			{
				session.Transaction.Rollback();
			}

			if (session != null)
			{
				session.Close();
                session.Dispose();
			}
		}
	}
}
